package com.etc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.etc.dao.ManagerDao;
import com.etc.dao.PersonDao;
import com.etc.dao.impl.ManagerDaoImpl;
import com.etc.dao.impl.PersonDaoImpl;
import com.etc.entity.PageModel;
import com.etc.entity.Person;
import com.etc.service.ManagerService;
import com.etc.service.impl.ManagerServiceImpl;

public class ManagerServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public ManagerServlet() {
		super();
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		    request.setCharacterEncoding("utf-8");
		    response.setCharacterEncoding("utf-8");
		    ManagerDao mdao=new ManagerDaoImpl();
		    PrintWriter out = response.getWriter();
		    String op="";
		    int id=0;
		    op=request.getParameter("op");
		    if(request.getParameter("id")!=null){
		     id=Integer.parseInt(request.getParameter("id"));
		    }
		    if("modify".equals(op)){
			double balance=Double.parseDouble(request.getParameter("balance"));
			if(balance>0){
			    mdao=new ManagerDaoImpl();
			    mdao.modifyBalance(id, balance);
				out.print("modify");
				out.flush();
				out.close();
				}
			}
		    else if("delete".equals(op)){
		    	mdao.removeUser(id);
		    	out.print("delete");
		    	out.flush();
				out.close();
		    }else if("getPersonListByPage".equals(op)){
				// 接收前端的请求参数
				int currentPage = 1;
				if (request.getParameter("currentPage") != null) {
					currentPage = Integer.parseInt(request.getParameter("currentPage"));
				}
				int pageSize = 2;
				if (request.getParameter("pageSize") != null) {
					pageSize = Integer.parseInt(request.getParameter("pageSize"));
				}
				int totalRecord = -1;
				if (request.getParameter("totalRecord") != null) {
					totalRecord = Integer.parseInt(request
							.getParameter("totalRecord"));
				}
				// 根据页面请求的信息，调用service，serivce调用DAO层，DAO层请求数据库获取当前搜索的信息包括列表和分页信息
				ManagerService service=new ManagerServiceImpl();
				PageModel<Person> pageMode = service.getPageModelListByPage(currentPage, pageSize, totalRecord);
				// 把JAVA对象转换成JSON的文本格式
				String jsonString = JSON.toJSONString(pageMode);
				out.print(jsonString);
				out.flush();
				out.close();
				}
		   
		
	}

}
